package com.ccc.test.mqtt.util;

import java.math.BigInteger;

/**
 * 十六进制转换工具类
 *
 * @author superC
 * @version 1.0.0
 * @date 2022/7/20
 */

public class MyHexUtils {

    public static String bytesToHexStr(byte[] bArray, int start, int len) {
        StringBuilder sb = new StringBuilder(bArray.length);
        String sTemp;
        for (int i = start; i < start + len; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static String byteToHexStr(byte b) {
        return Integer.toHexString(0xFF & b);
    }

    public static String hexToDec(String hexStr) {
        BigInteger number = new BigInteger(hexStr, 16);
        return number.toString();
    }

    public static String asciiToStr(byte[] arr) {
        StringBuilder sb = new StringBuilder();
        for (byte b : arr) {
            sb.append((char) b);
        }
        return sb.toString();
    }

    /**
     * 将16进制 ASCII转成字符串
     *
     * @param value
     * @return
     */
    public static String ASCIIToConvert(String value){
        StringBuffer sbu = new StringBuffer();
        for (int i = 0; i < value.length(); i += 2) {
            sbu.append((char) Integer.parseInt(value.substring(i, i + 2), 16));
        }
        return sbu.toString();
    }

    /**
     * 以小端模式将byte[]转成int
     */
    public static int bytesToIntLittle(byte[] src, int offset) {
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8));
        return value;
    }

    /**
     * 以小端模式将int转成byte[]
     *
     * @param value
     * @return
     */
    public static byte[] intToBytesLittle(int value) {
        byte[] src = new byte[2];
        src[1] = (byte) ((value >> 8) & 0xFF);
        src[0] = (byte) (value & 0xFF);
        return src;
    }

    /**
     * byte转换为二进制字符串
     *
     * @param b
     * @return
     */
    public static String byteArrToBinStr(byte b) {
        StringBuffer result = new StringBuffer();
        result.append(Long.toString(b & 0xff, 2) + ",");
        return result.toString().substring(0, result.length() - 1);
    }

}